<?php

class Campaign_IndexController extends Ac_Controller_Action
{
    public function campaignSamsungAction()
    {
        //redirect if lang not set.
        if (!in_array('lang', array_keys($this->_request->getParams()))) {
            $arr = array_keys((array) Zend_Locale::getBrowser());
            if (substr($arr[0], 0, 2) == 'zh') {
                $lang = 'tc';
            } else {
                $lang = 'en';
            }
            $this->_redirect($this->view->geturl('campaign-samsung','campaign', array('lang' => $lang), null, array('auto' => 1)));
        }
        
        unset($_GET['auto']);
        Zend_Registry::set('saved_GET', $_GET);
         
        
        //$arr = array_keys((array) Zend_Locale::getBrowser());
        if ($this->current_language == 'tc') {
             //$session = new Zend_Session_Namespace('current_language');
             //unset($session->current_language);
            //$script = 'index-zh';
            $script = 'end-zh';
        } else {
            //$script = 'index-en';
            $script = 'end-en';
        }
        //$this->_helper->_layout->setLayout('layout-campaign');
        $this->render($script);
    }

    public function campaignSamsungSuccessAction()
    {
        //campaign disabled
        $this->_redirect($this->view->geturl('campaign-samsung', 'campaign', null, null, null));
        
        //If the form is submitted
        if($this->_request->isPost()) {
            $errors = array();
            if (empty($_POST['email'])) {
                $errors[]=1;
            }
            if ($this->current_language == 'tc') {
                if (empty($_POST['fb_name'])) {
                    //$this->_redirect($this->view->geturl('campaign-samsung', 'campaign', null, null, array('error'=>3)));
                    $errors[]=3;
                }
                if (empty($_POST['name'])) {
                    //$this->_redirect($this->view->geturl('campaign-samsung', 'campaign', null, null, array('error'=>4)));
                    $errors[]=4;
                }
            }
            if (!preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['email'])) {
                $errors[]=2;
            }
            
            if (!empty($errors)) {
                $this->_redirect($this->view->geturl('campaign-samsung', 'campaign', null, null, array_merge($_POST, array('error' => implode(',',$errors)))));
            }
            
            $user  = Model_User::one(array('email' => new MongoRegex('/'.trim($_POST['email']).'/iu')));
            
            $exist = false;
            
            //Check if user already exist
            $user_to_send = null;
            if (!empty($user))
            {
                $exist = true;
                $password = false;
            }
            //If user does not exist
            else {
                //New user
                $password = Model_User::getNewPassword();
                $user = new Model_User();
                $user->email = $_POST['email'];
                $user->username = Model_User::generateUsername($_POST['email']);
                $user->password = Model_User::generatePassword($password);
                $user_to_send = $user;
            }
            
            $user->campaign_samsung_galaxy  = '1';
            $user->campaign_samsung_fb_name = $_POST['fb_name'];
            $user->campaign_samsung_name    = $_POST['name'];
            $user->save();
            $session = new Zend_Session_Namespace('newsletter');
            $session->email = $user->email;
            if ($exist) { 
                $session->exist = true; 
            } else { 
                $session->exist = false; 
            }
            //send email
            $subject = Zend_Registry::get('Zend_View')->t('You’ve signed up for winning a Samsung Galaxy Tab');
            Ac_Util::sendEmail($subject, '', $user->email, true, array('user' => $user_to_send, 'password' => $password), Ac_Mail::TEMPLATE_CAMPAIGN_SAMSUNG);            
            
            //Redirection to the success page for Loggedin User
            $lang = $this->current_language;
            if (empty($lang)) {
                $arr = array_keys((array) Zend_Locale::getBrowser());
                if (substr($arr[0], 0, 2) == 'zh') {
                    $lang = 'tc';
                } else {
                    $lang = 'en';
                }
            }
            $this->_redirect($this->view->geturl('campaign-samsung-success', 'campaign', array('lang' => $lang)));
        }
        
 
        $arr = array_keys((array) Zend_Locale::getBrowser());
        if ($this->current_language == 'tc') {
            $script = 'success-zh';
        } else {
            $script = 'success-en';
        }
 
        $this->view->list = Model_Category::all(array('path' => array('$size' => 1)));
        //$this->_helper->_layout->setLayout('layout-campaign');
        $this->render($script);
    }
    
    
    function campaignDomesticHelperAction() 
    {
        $this->addTitle('Domestic Helper? Advertize Yourself!');
        $category_id = '4cda3e818835c16810090200';
        $session = new Zend_Session_Namespace('post-an-ad');
        if ($this->_request->isGet()) {
            $session->unlockAll();
            $session->unsetAll();
        }
        $new = true;
        
                $classname = '';
        if(!empty($_GET['change']) && !empty($session->listing_started)) {
            $ad = Model_Listing_Preview::one(array('_id' => new MongoId($session->listing_started)));
            $new = false;
            if (empty($ad)) {
                $new = true;
                $ad = new Model_Listing_Preview();
                $ad->status = Model_Listing::STATUS_STARTED;
                $ad->save();
            }
        } elseif ($this->_request->isPost() ) {
            $classname = Model_Listing::getInstanceClassname((array)$category_id);
            $ad = Model_Listing_Preview::getInstance($classname, $_POST['adid']);            
        } else {
            $new = true;
            $ad = new Model_Listing_Preview();
            $ad->status = Model_Listing::STATUS_STARTED;
            $ad->save();
        }
        
        //var_dump($_POST, $classname, $ad);
        
        
        if (empty($ad->ca)) {
            $ad->ca = array();
            $ad->addCategory($category_id);
        }
        
        
        if ($this->_request->isPost() && !empty($_FILES)) {
            //var_dump($_POST);exit;
            //move_uploaded_file($_FILES['upload1']['tmp_name'], '/tmp/test.jpg');
            //var_dump($_FILES, is_uploaded_file($_FILES['upload1']['tmp_name']));exit;
            $_SERVER['HTTP_ADID'] = $ad->_id;
            $_SERVER['NOT_JSON'] = 1;
            //var_dump($_FILES);
            $res = Ac_Util::uploadListingPhotoProcess();
           // var_dump('file uploaded', $res);
            $classname = Model_Listing::getInstanceClassname((array)$category_id);
            $ad = Model_Listing_Preview::getInstance($classname, $ad->_id);
        }           
        
        if ($new) {
            $classname = Model_Listing::getInstanceClassname((array)$category_id);
            $ad = Model_Listing_Preview::getInstance($classname, $ad->_id);
        }
        
        $options = array(
            'viewscript' => 'index/maid/post-an-ad.phtml',
            'listing'    => $ad,
            'adid'       => $ad->_id,
            'category'   => array(Model_Category::find($category_id)),
        );
        
        
        $form = new Listing_Form_PostAnAddMaidForm($options);

        
        $form->populate((array)$_POST);
        //if default photo uploader used
        
        //var_dump($ad->photos);
          
        
        if ($this->_request->isPost() && $form->isValid($_POST)) {
            $form->save();
            Zend_Auth::getInstance()->clearIdentity();
            if(empty($this->loggedin_user)) {
                $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                $to_be_confirmed_ads->setExpirationSeconds(10000000);
                $arr = array();
                $arr[] = $ad->_id;
                $to_be_confirmed_ads->arr = $arr;
                $to_be_confirmed_ads->lock();
                
                $session = new Zend_Session_Namespace('return _url');
                $session->url = $this->view->geturl('campaign-domestic-helper-success','campaign');
                $this->_redirect($this->view->geturl('register','user'));
            } else {
                
            }
        } else {
        	//echo "<pre>";var_dump($form->getErrors(), $_POST);echo "</pre>";
        }
        
        $form->setAction($this->view->geturl('campaign-domestic-helper', 'campaign'));
        
        $this->view->form = $form;
        $this->render('maid/index');
    }
    
    public function campaignDomesticHelperSuccessAction()
    {
        $this->addTitle('Success - Domestic Helper? Advertize Yourself!');

        if(empty($this->loggedin_user)) {
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('campaign-domestic-helper', 'campaign'));
        }
        //echo '<pre>';print_r($_SESSION);exit;
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        $arr = (array) $to_be_confirmed_ads->arr;
        //var_dump($arr);
        //if (empty($arr)) {
        //    $this->_redirect($this->view->geturl('post-registration', 'user'));
        //}

        $ads = array();
        foreach ($arr as $ad_id) {
            $ad = Model_Listing::find($ad_id);
            
            //var_dump($ad->status);
            if (!empty($ad)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
                $ad->user = $this->loggedin_user->_id;
                
                $res = $ad->save();
                echo $ad->_id.'<br>';
            }
            //var_dump($ad->status, $res);
        }

        $to_be_confirmed_ads->unlock();        
        $to_be_confirmed_ads->unsetAll();
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->unsetAll();
        
        
        $this->view->list = Model_Category::all(array('path' => array('$size' => 1)));
        $this->render('maid/success');
    }     
    
    function campaignDomesticHelperTermsAction()
    {
        $this->render('maid/terms');
    }
    
    function commonAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/'.$campaign_id.'/index.html');
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }
    
    function headerAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/header.html');
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }
    
    function footerAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/footer.html');
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }
    
    function navAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/nav.html');
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }
    
    function asideAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/aside.html');
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }    
    
    function formAction()
    {
        $this->_helper->layout->disableLayout();
        $campaign_id = $this->_request->getParam('id');
        $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/form.html');
        
        //remove error block by default
        $ct = preg_replace('#(<!-- ERROR_BLOCK_START -->.*<!-- ERROR_BLOCK_END -->)#simu', '', $ct);
        $ct = str_replace(' [ERROR_CLASS]', '', $ct);
        echo $this->fixContent($ct, $campaign_id);
        exit;
    }
    
    protected function fixContent($ct, $campaign_id) 
    {
        //fix path
        if (preg_match_all('#<link href="([^"]*)"[^>]*>#i', $ct, $matches)) {
            foreach($matches[1] as $match) {
                $ct = str_replace($match, Ac_Util::getImageBaseUrl('/elements/campaign/'.$campaign_id.'/'.$match), $ct);
            }
        }

        if (preg_match_all('#<script src="([^:"]*)"[^>]*>#i', $ct, $matches)) {
            foreach($matches[1] as $match) {
                $ct = str_replace($match, Ac_Util::getImageBaseUrl('/elements/campaign/'.$campaign_id.'/'.$match), $ct);
            }
        }    
        
        if (preg_match_all('#<img src="([^\#"]*?)"[^>]*?>#i', $ct, $matches)) {
            foreach($matches[1] as $match) {
                $ct = str_replace($match, Ac_Util::getImageBaseUrl('/elements/campaign/'.$campaign_id.'/'.$match), $ct);
            }
        }
        
        return $ct;
    }
    
    function processAction()
    {
        //because the form might change often, we will deal with it the old fashion way
        $this->_helper->layout->disableLayout();
        $campaign_id = (int)$this->_request->getParam('id');
        $errors = array();
        $obj = new Model_Campaign_User();
        $obj->campaign_id = (int) $campaign_id;
        $do_not_save = false;
        //if ($campaign_id == 1) {
            //email
            if (empty($_GET['email'])) {
                $errors['email'] = 1;
            } else {
                
                if($user = Model_Campaign_User::one(array('email' => $_GET['email'], 'campaign_id' => $campaign_id))) {
                    $do_not_save = true;
                }
                $obj->email = $_GET['email'];
            }

            //facebook name
            if (empty($_GET['fb_name'])) {
                $errors['fb_name'] = 1;
            } else {
                $obj->fb_name = $_GET['fb_name'];
            }

            //know_ac
            if (empty($_GET['know_ac'])) {
                //$errors['know_ac'] = 1;
            } else {
                $obj->know_ac = $_GET['know_ac'];
            }
            if(!empty($_GET['q1'])) {
                $obj->q1 = $_GET['q1'];
            }            
        //} 
        
        //echo '<pre>';var_dump($_GET, $errors);exit;
        if(empty($errors)) {
            if (!$do_not_save) {
                $obj->save();
            }
            
            if($campaign_id == 12){
				//send email
				$contact_name = $_GET['contact_name'];
				$tel_num  = $_GET['tel'];
				$email_add = $_GET['email'];
				$website = $_GET['url'];
				$language  = "tc";
		
		        $subject = Zend_Registry::get('Zend_View')->t('Subscription of Free Bulk Listing Service - TEST');
		        Ac_Util::sendEmail($subject, '', 'freebulklisting@asiaclassified.com', true, array('contact_name' => $contact_name, 'tel_num' => $tel_num, 'email_add' => $email_add, 'website' => $website, 'language' => $language), Ac_Mail::TEMPLATE_CAMPAIGN_BULKLISTING);  
				//$this->render('maid/terms');
			}
			
            $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/success.html');
            echo $this->fixContent($ct, $campaign_id);
        } else {
            $ct = file_get_contents(ROOT_PATH . '/public/elements/campaign/assets/'.$campaign_id.'/form.html');
            $ct = str_replace(' [ERROR_CLASS_EMAIL]', ' error ', $ct);
            $ct = str_replace(' [ERROR_CLASS_FBNAME]', ' error ', $ct);
            $ct = str_replace(' [ERROR_CLASS_KNOWAC]', ' error ', $ct);
/*            
            if (!empty($errors['email'])) {
                $ct = str_replace(' [ERROR_CLASS_EMAIL]', ' error ', $ct);
            }
            if(!empty($errors['fb_name'])) {
                $ct = str_replace(' [ERROR_CLASS_FBNAME]', ' error ', $ct);
            } 
            if(!empty($errors['know_ac'])) {
                $ct = str_replace(' [ERROR_CLASS_KNOWAC]', ' error ', $ct);
            }
 */
            echo $this->fixContent($ct, $campaign_id);            
        }
        exit;
    }
    
    public function mailTestAction()
    {
		//send email
		$contact_name = "John";
		$tel_num  = "12345";
		$email_add = "yahoo@yahoo.com";
		$website = "google.com";
		$language  = "en";

        $subject = Zend_Registry::get('Zend_View')->t('Subscription of Free Bulk Listing Service - TEST');
        Ac_Util::sendEmail($subject, '', 'freebulklisting@asiaclassified.com', true, array('contact_name' => $contact_name, 'tel_num' => $tel_num, 'email_add' => $email_add, 'website' => $website, 'language' => $language), Ac_Mail::TEMPLATE_CAMPAIGN_BULKLISTING);  
		$this->render('maid/terms');
	}
}
